<?php if (!defined("_ECRIRE_INC_VERSION")) return; if (class_exists('FeedbackFormidable')) return;
/**
 * Feedback plugin
 *
 * @author     Aleksey Yaroshchuk (aleksey.yaroshchuk@gmail.com)
 * @license    GNU/GPL
 * @package    plugins
 * @subpackage feedback
 * @copyright  (c) Aleksey Yaroshchuk 2011-2012
 * @link       http://www.spip-contrib.net/AlohaCart
 */
 
include_spip('inc/filtres');
include_spip('inc/texte');
include_spip('functions/pdk_common');

/**
 *  Class that helps to work with Formidable plugin
 *
 *  @author Aleksey Yaroshchuk (aleksey.yaroshchuk@gmail.com) 
 */
class FeedbackFormidable {
    /**
     *  Creates auteurs emails array from auteurs ids
     *  @param array $auteur_ids Array of auteurs ids, or single auteur id
     *  @return array Auteur emails or empty array
     */
    public static function CreateAuteursEmailsArray($auteur_ids) {
        $emails = array(); 
		if (!is_array($auteur_ids) and intval($auteur_ids)){
			$auteur_ids = array($auteur_ids);
		}
		if (is_array($auteur_ids)){
			$auteur_ids = array_map('intval', $auteur_ids);
			$emails = sql_allfetsel(
				'email',
				'spip_auteurs',
				sql_in('id_auteur', $auteur_ids)
			);
			$emails = array_map('reset', $emails);
		}
        return $emails;
    }
    
    /**
     * Checks uploaded files
     * @param string $error Error of uploading process. If empty, all is OK
     * @param array $options Array of options
     * @return bool True if OK, False otherwise
     */
    public static function CheckFiles(&$error, $options=array()) {
        $min_files = isset($options['min_files'])?$options['min_files']:0;
        $nom = isset($options['nom'])?$options['nom']:'files_1';
        $uploaded = 0;
        foreach ($_FILES as $file=>$file_data) {
            if ($file_data['name'] && strstr($file, $nom)!==false)
                $uploaded++;
        }        
        if ($uploaded < $min_files) {
            $error = _T('feedback:min_files_not_loaded')/*.': '.$min_files*/;
            return false;
        }
        
        return true;
    }
    
    /**
     *  Uploads files for file field of current form
     *  This function will upload all files found in $_FILES array that have name starting with saisie name
     *  and put all their data in $GLOBALS['uploaded_files_data_'.$nom] array, 
     *  so later it can be used, for example, in traiter functions
     *  
     *  @param string $error Error of uploading process. If empty, all is OK
     *  @param array $options Array of options:
     *                        nom - Saisie name (required, default files_1)
     *                        upload_path - Relative or absolute path where files will be uploaded
     *                        allowed_types - Allowed files format
     *                        max_size - Max file size
     * 
     */
    public static function UploadFiles(&$error, $options=array()) {        
        include_spip('classes/pdk_upload');
        $nom = isset($options['nom'])?$options['nom']:'files_1';
    
        $config = array();
        $config['upload_path'] = isset($options['upload_path']) && $options['upload_path'] ? $options['upload_path'] : _DIR_TMP;
        $config['allowed_types'] = isset($options['allowed_types']) && $options['allowed_types'] ? $options['allowed_types'] : '*';        
        $config['max_size'] = isset($options['max_size']) && $options['max_size'] ? $options['max_size'] : 2048;
        //$config['encrypt_name'] = isset($this->config['attach_files']['encrypt_name']) && $this->config['attach_files']['encrypt_name'] ? true : false;
        $config['encrypt_name'] = true;
        $uploader = new pdk_Upload($config);
        if ($_FILES && FeedbackFormidable::CheckFiles($error, $options))
            foreach ($_FILES as $file=>$data) {                
                if (!$data['name'] || strstr($file, $nom)===false) continue; // Left out empty file fields and files that do not belong to our field
                 
                switch ($options['where_to_save']) {
                    case 'folder':
                        if ($uploader->do_upload($file)) {
                            $file_data = $uploader->data();
                            /*
                            // Add SPIP path to file data. Later it can be used to create public link on file
                            $public_link = $config['upload_path'];
                            if ($public_link[strlen($public_link)-1] != '/')
                                $public_link .= '/';
                            $file_data['public_link'] = $public_link . $file_data['file_name'];*/  
                            // Save file data into globals, so later we can use it in traiter function
                            $GLOBALS['uploaded_files_data_'.$nom][$file] = $file_data;
                        } else {
                            $error = _T("feedback:file_load_error");
                        }
                        break;
                    case 'document':
                        $document_mdl = pdk_load_class('pdk_document_model','classes');
                        $document_mdl->document_input_name = $file;
                        $document_mdl->allowed_types = $config['allowed_types'];
                        $document_mdl->max_size = $config['max_size'];
                        $file_data = array();
                        if ($document_mdl->UploadDocumentFile(array(), &$file_data)) {                            
                            $GLOBALS['uploaded_files_data_'.$nom][$file] = $file_data;
                        } else {                    
                            $error = _T("feedback:file_load_error");
                        }                        
                        break;         
                }
            }
        if ($error) {
            //TODO: Удалить успешно загруженные файлы в случае ошибки
        } 
    }
} 
?>